#!/bin/bash

DISPLAY=:0

if [ -z "$1" ]
then
	echo "Usage: `basename $0` <image1> <image2> ... "
	exit 1
fi

exists=`ps -e | grep "autostitch.exe"`
if [ "$exists" ]; then
	echo "An instance of autostitch is already running."
	exit 1
fi
	
no_images="$#"
#echo "Using "$no_images" images"
images=""
first_images=""

count=0
while [ $1 ]; do
	images=$images"\""$1"\" "
	if [ $count -lt 3 ]; then 
		first_images=$first_images"\""$1"\" "
	fi
	let count=count+1
	shift
done

wine /home/tom/siweather/scripts/autostitch.exe &> out.txt &

open_time=0
opened=`wmctrl -l | grep -w "autostitch"`
while [ -z "$opened" ]; do
	sleep 0.2
	open_time=`echo "$open_time+0.2" | bc`
	opened=`wmctrl -l | grep -w "autostitch"`
done
# echo "Took "$open_time" seconds to open autostitch"

sleep 0.5
################ OPEN IMAGES ###################
xte "key Alt_L" 
xte "key Down" 
xte "key Return" 
xte "str $first_images"
xte "key Return"

sleep 3
progress=`fgrep "Access denied" out.txt | wc -l`
failed=`cat out.txt | grep "No image matches found"`

while [ $progress -lt 1 -a -z "$failed" ]; do
	sleep 0.2
	progress=`fgrep "Access denied" out.txt | wc -l`
	failed=`cat out.txt | grep "No image matches found"`
done

if [ "$failed" ]; then
	echo Failed
	xte "key Alt_L"
	xte "key Down"
	xte "key Down"
	xte "key Return"
	sleep 2
	killall autostitch.exe
	exit
fi

sleep 0.5
################ EDIT SETTINGS #################
xte "key Alt_L" 
xte "key Right"
xte "key Down" 
xte "key Return"

for i in {1..5}; do
   xte "key Tab"
done
xte "str 320"
#xte "key Up" #uncomment to set height output size to %100
#xte "key Up"
#xte "key Up"

for i in {1..10}; do
   xte "key Tab"
done
xte "key Up"
xte "key Up"
xte "key Return"

sleep 0.5
################ OPEN IMAGES ###################
xte "key Alt_L" 
xte "key Down" 
xte "key Return" 
xte "str $images"
xte "key Return"

sleep 3
progress=`fgrep "Access denied" out.txt | wc -l`

while [ $progress -lt 1 ]; do
	sleep 0.2
	progress=`fgrep "Access denied" out.txt | wc -l`
done

sleep 0.5
############### RUN STITCH ######################
xte "key Alt_L" 
xte "key Right"
xte "key Right"
xte "key Down" 
xte "key Return"
sleep 3
progress=`fgrep "Access denied" out.txt | wc -l`

while [ $progress -lt 2 ]; do
	sleep 0.2
	progress=`fgrep "Access denied" out.txt | wc -l`
done

sleep 0.5
############### EXIT AUTOSTITCH #################
xte "key Alt_L"
xte "key Down"
xte "key Down"
xte "key Return"

rm pano.txt

exit 0
